let viewer, scene, editHandler;

export function init(e) {
  viewer = e;
  scene = e.scene;
}

// 画线
export function drawLine(callback) {
  const positions = [];
  let poly, entity, drawingEntity;
  let isDrawing = true;
  let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  let polyLineEntity = (function () {
    function _(positions) {
      // polyline 配置
      this.options = {
        name: "polyline",
        polyline: {
          show: true,
          positions: [],
          material: Cesium.Color.GREEN,
          width: 3,
        },
      };
      this.positions = positions;
      this._init();
    }

    _.prototype._init = function () {
      let _self = this;
      this.options.polyline.positions = new Cesium.CallbackProperty(
        function () {
          return _self.positions;
        },
        false
      );
      drawingEntity = entity = viewer.entities.add(this.options);
    };
    return _;
  })();
  handler.setInputAction(function (movement) {
    let ent = viewer.selectedEntity;
    // 当前选中的entity不是绘制的entity，就return。实现绘制时也能选择
    if (ent && drawingEntity !== ent) {
      return;
    }
    isDrawing = true;
    let cartesian = viewer.scene.pickPosition(movement.position);
    if (positions.length == 0) {
      positions.push(cartesian.clone());
    }
    positions.push(cartesian);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  handler.setInputAction((movement) => {
    let cartesian = viewer.scene.pickPosition(movement.endPosition);
    if (positions.length >= 2) {
      if (!Cesium.defined(poly)) {
        poly = new polyLineEntity(positions);
      } else {
        if (cartesian != undefined) {
          positions.pop();
          positions.push(cartesian);
        }
      }
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  handler.setInputAction((movement) => {
    positions.pop();
    isDrawing = false;
    handler = handler && handler.destroy(); // clear and empty the handler.
    callback && callback(entity);
    // 继续绘制
    // this.drawLine(this.handleEdit);
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}
// 编辑
export function handleEdit(entity,isEditZ=false) {
  if (!entity) {
    editHandler && editHandler.deactivate();
    return;
  }
  if (!editHandler) {
    editHandler = new Cesium.EditHandler(viewer, entity);
    editHandler.isEditZ = isEditZ; // 是否开启编辑Z值
    editHandler.activate();
  } else {
    editHandler.deactivate();
    editHandler.setEditObject(entity);
    editHandler.activate();
  }
}
// 下载文件
export function handleSaveClick() {
  let funDownload = function (content, filename) {
    let eleLink = document.createElement("a");
    eleLink.download = filename;
    eleLink.style.display = "none";
    // 字符内容转变成blob地址
    let blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
  };
  let entities = new Cesium.EntityCollection();
  let dataSources = viewer.dataSources;
  for (let i = 0, j = dataSources.length; i < j; i++) {
    for (let v of dataSources.get(i).entities.values) {
      entities.add(v);
    }
  }
  for (let v of viewer.entities.values) {
    entities.add(v);
  }

  if (entities.values.length) {
    let promise = Cesium.exportKml({ entities: entities });
    promise.then(function (e) {
      funDownload(e.kml, new Date().getTime() + ".kml");
    });
  } else {
    alert("当前场景没有entities实体");
  }
}
// 打开文件
export function handleOpenClick() {
  let fileInput = document.querySelector(".file");

  fileInput.onchange = function (evt) {
    let files = evt.target.files;
    if (files.length > 0) {
      let file = evt.target.files[0];
      let fileReader = new FileReader();
      // console.log(file)
      fileReader.onload = function () {
        viewer.dataSources
          .add(
            Cesium.KmlDataSource.load(new Blob([this.result]), {
              camera: viewer.scene.camera,
              canvas: viewer.scene.canvas,
            })
          )
          .then(function (kmlDataSource) {
            let entities = kmlDataSource.entities;
            let item = entities.values[entities.values.length - 1];
            self.handleEdit(item);
            viewer.zoomTo(entities);
          });
        fileInput = null;
        fileReader = null;
      };
      fileReader.readAsText(file);
    }
    fileInput.value = null;
  };
  fileInput.click();
}

export function clean() {
  if (editHandler) {
    editHandler.clear()
    editHandler.deactivate()
  }
  viewer.entities.removeAll()
  let dataSources = viewer.dataSources
  dataSources.removeAll()
}
